package cn.tsyz.local.modules.auth.controller;

import cn.tsyz.local.common.exception.BusinessException;
import cn.tsyz.local.common.exception.ErrorCode;
import cn.tsyz.local.common.result.Result;
import cn.tsyz.local.modules.auth.dto.LoginRequest;
import cn.tsyz.local.modules.auth.dto.UserInfo;
import cn.tsyz.local.modules.user.model.User;
import cn.tsyz.local.modules.user.service.UserService;
import cn.tsyz.local.shared.security.JwtUtil;
import cn.tsyz.local.util.CookieUtil;
import cn.tsyz.local.util.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller  // 改为@Controller而不是@RestController
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private CookieUtil cookieUtil;

    /**
     * 显示登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        log.info("显示登录页面");
        // 检查用户是否已经登录
        User currentUser = UserContextHolder.getCurrentUser();
        if (currentUser != null) {
            log.info("用户 {} 已登录，重定向到主页", currentUser.getUsername());
            return "redirect:/"; // 已登录则重定向到主页
        }

        return "login"; // 返回templates/login.html模板
    }

    /**
     * 处理登录请求
     */
    @PostMapping("/api/login")
    @ResponseBody  // 这个方法返回JSON数据
    public Result<String> login(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        log.info("处理登录请求，用户名: {}", loginRequest.getUsername());

        try {
            // 验证用户名和密码
            User user = userService.findByUsername(loginRequest.getUsername());

            if (user == null) {
                log.warn("登录失败：用户 {} 不存在", loginRequest.getUsername());
                throw new BusinessException(ErrorCode.USERNAME_OR_PASSWORD_ERROR);
            }

            if (!user.getEnabled()) {
                log.warn("登录失败：用户 {} 已被禁用", loginRequest.getUsername());
                throw new BusinessException(ErrorCode.USER_DISABLED);
            }

            if (!userService.checkPassword(loginRequest.getPassword(), user.getPassword())) {
                log.warn("登录失败：用户 {} 密码错误", loginRequest.getUsername());
                throw new BusinessException(ErrorCode.USERNAME_OR_PASSWORD_ERROR);
            }

            // 生成Token
            String token = jwtUtil.generateToken(user.getId(), user.getUsername());

            // 设置Token到Cookie
            cookieUtil.setTokenCookie(response, token);

            log.info("用户 {} 登录成功", user.getUsername());
            return Result.success("登录成功", token);

        } catch (BusinessException e) {
            log.warn("登录业务异常: {}", e.getMessage());
            throw e; // 重新抛出业务异常
        } catch (Exception e) {
            log.error("登录系统异常", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败");
        }
    }

    /**
     * 处理登出请求
     */
    @PostMapping("/api/logout")
    @ResponseBody
    public Result<String> logout(HttpServletResponse response) {
        log.info("用户登出");
        // 删除Token Cookie
        cookieUtil.removeTokenCookie(response);
        return Result.success("登出成功");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/api/user/info")
    @ResponseBody
    public Result<UserInfo> getCurrentUserInfo() {
        User currentUser = UserContextHolder.getCurrentUser();
        if (currentUser != null) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(currentUser.getId());
            userInfo.setUsername(currentUser.getUsername());
            userInfo.setEmail(currentUser.getEmail());
            return Result.success(userInfo);
        }
        log.warn("获取用户信息失败：用户未登录");
        throw new BusinessException(ErrorCode.UNAUTHORIZED);
    }
}
